package client

import (
	"context"
	"github.com/milkbobo/fishgoweb/language"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"miners-monitor/models/common"
)

type ClientAoModel struct {
	common.BaseModel
	CommonFunc common.CommonFunc
	ClientDb   ClientDbModel
}

func (this *ClientAoModel) Search(filter Client) Clients {

	opts := this.CommonFunc.GetPaging()

	result := Clients{}
	result.Data = this.FindByStruct(filter, opts)
	result.Total = this.ClientDb.CountDocuments(filter, options.Count())
	return result
}

func (this *ClientAoModel) FindOne(filter Client, opts *options.FindOneOptions) Client {
	mongoResult := this.ClientDb.FindOne(filter, opts)
	result := Client{}
	err := mongoResult.Decode(&result)
	if err == mongo.ErrNoDocuments {
		return Client{}
	} else if err != nil {
		panic(err)
	}
	return result
}

func (this *ClientAoModel) FindByStruct(filter Client, opts *options.FindOptions) []Client {
	filterBsonD := this.ClientDb.StructToBsonDAndAppendClientId(filter)

	mongoResult := this.ClientDb.Find(filterBsonD, opts)
	result := []Client{}
	err := mongoResult.All(context.TODO(), &result)
	if err == mongo.ErrNoDocuments {
		return []Client{}
	} else if err != nil {
		panic(err)
	}
	for i, client := range result {
		client.Password = ""
		result[i] = client
	}
	return result
}

func (this *ClientAoModel) Del(clientId string) *mongo.DeleteResult {
	return this.ClientDb.Del(clientId)
}

func (this *ClientAoModel) Upsert(update Client) {
	this.ClientDb.Upsert(update)
}

func (this *ClientAoModel) Update(update Client) {
	this.ClientDb.Update(update)
}

func (this *ClientAoModel) IsLoginAndCheckoutAuth(auth string) Client {
	if auth == "" {
		language.Throw(1, "参数权限不能为空")
	}

	result := this.IsLogin()

	if len(result.Authority) == 0 {
		language.Throw(1, "权限为空，联系管理员给你添加权限")
	}

	for _, s := range result.Authority {
		if s == ClientAuthorityEnum.AccountManagement {
			return result
		}
	}

	for _, s := range result.Authority {
		if s == auth {
			return result
		}
	}

	language.Throw(1, "抱歉，你没有该页面的权限")
	return Client{}
}

func (this *ClientAoModel) IsLogin() Client {

	sess, err := this.Session.SessionStart()
	if err != nil {
		this.Log.Debug("%+v", err)
		panic("session启动失败:" + err.Error())
	}

	defer sess.SessionRelease()

	clientId := sess.Get("clientId")

	if clientId == nil {
		language.Throw(1, "未登陆，请重新登陆")
	}
	clientStr := clientId.(string)
	result := this.FindOne(Client{ClientId: clientStr}, options.FindOne())
	if result.ClientId == "" {
		language.Throw(1, "该登陆用户不存在,请重新登陆")
	}
	return result
}
